package com.quanquan.store.controller.marketActivity;

import DTO.PageDTO;
import DTO.user.UserDTO;
import DTO.user.UserInfoDTO;
import com.alibaba.fastjson.JSON;
import com.quanquan.store.dto.CouponDTO;
import com.quanquan.store.dto.IdDTO;
import com.quanquan.store.dto.marketActivity.PaperPlaneInfoDTO;
import com.quanquan.store.entity.marketActivity.paperPlane.PaperPlane;
import com.quanquan.store.entity.marketActivity.paperPlane.PaperPlaneCode;
import com.quanquan.store.entity.marketActivity.paperPlane.PaperPlaneGift;
import com.quanquan.store.entity.marketActivity.paperPlane.PaperPlaneRecord;
import com.quanquan.store.request.CouponRequest;
import com.quanquan.store.request.marketActivity.PaperPlaneRequest;
import com.quanquan.store.service.CouponService;
import com.quanquan.store.service.marketActivity.PaperPlaneService;
import enums.ResCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import utils.DateUtils;
import utils.StringUtil;
import utils.StringUtils;
import web.response.ResultBody;

import java.util.*;

/**
 * @ClassName PaperPlaneController
 * @Description
 * @Author Owen
 * @Date 2019/9/17 0017 下午 2:31
 * @Version V1.0
 **/
@RestController
@RequestMapping("/marketActivity/paperPlane")
@Slf4j
public class PaperPlaneController {

    @Autowired
    private PaperPlaneService paperPlaneService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CouponService couponService;

    /**
     * 根据id获取活动信息
     * @param request
     * @return
     */
    @PostMapping("/getActivityInfo")
    public ResultBody getActivityInfo(@RequestBody PaperPlaneRequest request) {

        if (null == request.getId() || StringUtils.isEmpty(request.getUserId())) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        PaperPlane paperPlane = paperPlaneService.getById(request.getId());
        if (null == paperPlane || paperPlane.getStatus() != 1) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动信息查询失败或已下架");
        }

        //进行中
        Integer goingStatus = 0;
        if(DateUtils.compare_date(paperPlane.getStartTime(),new Date()) > 0){
            goingStatus = -1;//未开始
        }
        if(DateUtils.compare_date(paperPlane.getEndTime(),new Date()) <= 0){
            goingStatus = 1;//已结束
        }

        PaperPlaneInfoDTO paperPlaneInfoDTO = new PaperPlaneInfoDTO();
        BeanUtils.copyProperties(paperPlane, paperPlaneInfoDTO);
        paperPlaneInfoDTO.setGoingStatus(goingStatus);

        List<String> bannerList = Arrays.asList(paperPlane.getBanner().split(","));
        paperPlaneInfoDTO.setBannerList(bannerList);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success", paperPlaneInfoDTO);

    }


    /**
     * 用户提交飞机编码
     * @param paperPlaneRequest
     * @return
     */
    @PostMapping("/addMemberPlaneCode")
    public ResultBody addMemberPlaneCode(@RequestBody PaperPlaneRequest paperPlaneRequest){

        if(StringUtil.isEmpty(paperPlaneRequest.getUserId()) || StringUtil.isEmpty(paperPlaneRequest.getPlaneCode()) || null == paperPlaneRequest.getActivityId()){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        PaperPlaneCode paperPlaneCode = paperPlaneService.getByCodeAndActivityId(paperPlaneRequest.getPlaneCode(),paperPlaneRequest.getActivityId());
        if(null == paperPlaneCode){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "编码不存在");
        }

        if(paperPlaneCode.getState() != 1){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "编码无效");
        }

        if(paperPlaneCode.getStatus() != 0){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "编码已使用");
        }

        paperPlaneCode.setJoinTime(new Date());
        paperPlaneCode.setUserId(paperPlaneRequest.getUserId());
        paperPlaneCode.setStatus(1);
        paperPlaneService.savePlaneCode(paperPlaneCode);

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "恭喜您编码已提交成功，9月28日公布瓜分大奖，请留意小程序页面消息");
    }


    /**
     * 开奖
     * @param paperPlaneRequest
     * @return
     */
    @PostMapping("/drawingGift")
    public ResultBody drawingGift(@RequestBody PaperPlaneRequest paperPlaneRequest){
        if(null == paperPlaneRequest.getActivityId() || null == paperPlaneRequest.getDifficulty()){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        List<String> userList = paperPlaneService.getUserIdByDifficulty(paperPlaneRequest.getActivityId(), paperPlaneRequest.getDifficulty());
        if(userList.size() < 1){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "人数不足");
        }
        List<PaperPlaneGift> giftListByDifficulty = paperPlaneService.getGiftListByDifficulty(paperPlaneRequest.getActivityId(), paperPlaneRequest.getDifficulty());
        if(giftListByDifficulty.size() < 1){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "无奖品");
        }

        int giftCount = 0;
        int giftRemainCount = 0;
        for (PaperPlaneGift gift:giftListByDifficulty) {
            if (gift.getRemainTotal() < 1){
                continue;
            }
            giftCount = gift.getRemainTotal()/userList.size();
            giftRemainCount = gift.getRemainTotal()%userList.size();

            PaperPlaneRecord record = null;
            for (int i = 0; i < userList.size(); i++) {

                if(i == (userList.size() - 1)){
                    giftCount = giftCount + giftRemainCount;
                }

                CouponRequest couponRequest = new CouponRequest();
                couponRequest.setUserId(userList.get(i));
                couponRequest.setId(gift.getCouponId());
                couponRequest.setCount(giftCount);
                System.out.println("发券结果："+JSON.toJSONString(couponRequest));
                String sendResult = couponService.sendCoupon(couponRequest);
                System.out.println("发券结果："+sendResult);
                if("发券成功".equals(sendResult)){
                    record = new PaperPlaneRecord();
                    record.setActivityId(paperPlaneRequest.getActivityId());
                    record.setCouponId(gift.getCouponId());
                    record.setDifficulty(paperPlaneRequest.getDifficulty());
                    record.setGiftCount(giftCount);
                    record.setGiftId(gift.getId());
                    record.setGiftType(gift.getGiftType());
                    record.setUserId(userList.get(i));
                    record.setCreateTime(new Date());
                    paperPlaneService.saveOrUpdateRecord(record);

                    paperPlaneService.substractStock(gift.getId(),giftCount);
                }

            }
        }


        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success");
    }


    /**
     * 获取纸飞机开奖结果
     * @param paperPlaneRequest
     * @return
     */
    @PostMapping("/getPaperPlaneResult")
    public ResultBody getPaperPlaneResult(@RequestBody PaperPlaneRequest paperPlaneRequest){
        if(StringUtil.isEmpty(paperPlaneRequest.getUserId()) || null == paperPlaneRequest.getActivityId()){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        int joinCount = paperPlaneService.countByStatus(paperPlaneRequest.getActivityId(),1);
        int enterCount = paperPlaneService.countByStatus(paperPlaneRequest.getActivityId(),2);

        List<PaperPlaneRecord> paperPlaneRecordList = paperPlaneService.getPaperPlaneRecordList(paperPlaneRequest.getActivityId());

        List<Object> userResult = new LinkedList<>();
        List<Object> recordList = new LinkedList<>();

        Map<String,Object> map = null;
        for (PaperPlaneRecord record:paperPlaneRecordList) {
            map = new HashMap<String,Object>();
            IdDTO idDTO = new IdDTO();
            List<String> ids = new LinkedList<>();
            ids.add(record.getUserId());
            idDTO.setForeignKeyIds(ids);

            UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/query_by_id_list", idDTO, UserInfoDTO.class);
            if(null == userInfoDTO || userInfoDTO.getUserDTOS().size() < 1){
                continue;
            }
            UserDTO userDTO = userInfoDTO.getUserDTOS().get(0);
            if(null == userDTO || StringUtil.isEmpty(userDTO.getPhone())){
                continue;
            }
            String phone = userDTO.getPhone();
            map.put("phone",phone.substring(0,3) + "****" + phone.substring(7,phone.length()));

            CouponDTO couponDTO = couponService.queryDetailsById(record.getCouponId());
            if(null == couponDTO){
                continue;
            }
            map.put("giftName",couponDTO.getName());

            int giftCount = paperPlaneService.sumGiftCountByUserIdAndCouponId(paperPlaneRequest.getActivityId(), record.getUserId(), record.getCouponId());

            map.put("giftCount",giftCount);
            recordList.add(map);
            if(record.getUserId().equals(paperPlaneRequest.getUserId())){
                userResult.add(map);
            }
        }

        Map<String,Object> result = new HashMap<>();
        result.put("joinCount",joinCount);
        result.put("enterCount",enterCount);
        result.put("userResult",userResult);
        result.put("recordList",recordList);

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success",result);
    }


    /**
     * 后台列表
     * @param request
     * @return
     */
    @PostMapping("/getAllPlaneList")
    public ResultBody getAllPlaneList(@RequestBody PaperPlaneRequest request){
        PageDTO pageDTO = paperPlaneService.findAllPlaneByPage(request);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(),"success",pageDTO);
    }

    /**
     * 后台列表
     * @param request
     * @return
     */
    @PostMapping("/getAllPlaneCodeList")
    public ResultBody getAllPlaneCodeList(@RequestBody PaperPlaneRequest request){
        PageDTO pageDTO = paperPlaneService.findAllPlaneCodeByPage(request);
        log.info(JSON.toJSONString(pageDTO));
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(),"success",pageDTO);
    }

    @PostMapping("/editCode")
    public ResultBody editCode(@RequestBody PaperPlaneRequest request){
        if(StringUtil.isEmpty(request.getPlaneCode()) || null == request.getDifficulty() || null == request.getActivityId()){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        PaperPlaneCode paperPlaneCode = paperPlaneService.getByCodeAndActivityId(request.getPlaneCode(),request.getActivityId());
        if(null == paperPlaneCode){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "编码不存在");
        }

        if(paperPlaneCode.getState() != 1){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "编码无效");
        }

        if(paperPlaneCode.getStatus() == 0){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "该编码未在用户端提交");
        }

        if(paperPlaneCode.getStatus() == 2){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "请勿重复录入");
        }

        paperPlaneCode.setEnterTime(new Date());
        paperPlaneCode.setStatus(2);
        paperPlaneCode.setDifficulty(request.getDifficulty());
        paperPlaneService.savePlaneCode(paperPlaneCode);

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "编码录入成功");
    }

}
